<template>
  <div class="container">
    <div class="container_page">
      <page-header :showImg="false"></page-header>
      <div class="box" v-if="payResult">
        <div class="result">
          <div class="logo">
            <img
              v-if="payResult.success == 1"
              :src="require('@/assets/img/pay/ic_success.svg')"
            />
            <img v-else :src="require('@/assets/img/pay/ic_failed@2x.png')" />
          </div>
          <div
            class="tip "
            :class="{
              error: payResult.success != 1
            }"
          >
            {{ $t(successTpye[payResult.success]) }}
          </div>
        </div>
        <div class="detail_card" v-if="orderInfo">
          <div class="list_box">
            <div class="row">
              <div class="item">
                <div class="key">{{ $t('home_duration') }}</div>
                <div class="value" v-if="orderInfo.useDuration > 0">
                  {{ getDuration(orderInfo.useDuration * 1000) }}
                </div>
                <div class="value" v-else>
                  {{ getDuration(Date.now() - orderInfo.createTime) }}
                </div>
              </div>
            </div>
            <div class="row">
              <div class="item">
                <div class="key">{{ $t('order_orderAmount') }}</div>
                <div class="value">
                  {{
                    orderInfo.orderAmount | amountFormats($currencyVal.symbol)
                  }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="detail_card">
          <div class="title">{{ $t('order_paymentDetails2') }}</div>
          <div class="list_box">
            <div
              class="row"
              v-if="orderInfo && orderInfo.plateCouponAmount > 0"
            >
              <div class="row-title">{{ $t('pay_couponAndDiscount') }}</div>
              <div class="item">
                <div class="key">
                  <img
                    :src="require('@/assets/img/order/ic_coupon@2x.png')"
                    alt=""
                  />
                  <span class="label">{{ $t('order_discount') }}</span>
                </div>
                <div class="value">
                  {{
                    orderInfo.plateCouponAmount
                      | amountFormats($currencyVal.symbol)
                  }}
                </div>
              </div>
            </div>
            <div class="row" v-if="payResult.payOrderNo">
              <div class="row-title">{{ $t('pay_billing') }}</div>
              <div class="item">
                <div class="key">{{ $t('pay_transactionNo') }}</div>
                <div class="value">{{ payResult.payOrderNo }}</div>
              </div>
            </div>
            <div class="row">
              <div class="item">
                <div class="key">{{ $t('home_for') }}</div>
                <div class="value payment">
                  {{ $t(payType[payResult.type]) }}
                </div>
              </div>
              <div class="row" v-if="payResult.taxAmount > 0">
                <div class="item">
                  <div class="key">
                    {{ $t('order_tax') + payResult.tax + '%' }}
                  </div>
                  <div class="value payment">
                    {{
                      payResult.taxAmount | amountFormats($currencyVal.symbol)
                    }}
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="item">
                  <div class="key">
                    {{
                      payResult.taxAmount > 0
                        ? $t('order_pay_include_tax')
                        : $t('order_paymentAmount')
                    }}
                  </div>
                  <div class="value payment">
                    {{ payResult.amount | amountFormats($currencyVal.symbol) }}
                  </div>
                </div>
              </div>
              <div class="row" v-if="payResult.paymentMethod">
                <div class="item">
                  <div class="key">{{ $t('order_paymentMethod') }}</div>
                  <div class="value payment">
                    {{ $t(payMethodType[payResult.paymentMethod])
                    }}<span v-if="payResult.bankNo"
                      >({{ payResult.bankNo | stateFormats }})</span
                    >
                  </div>
                </div>
              </div>
              <div class="row" v-if="payResult.failedReason">
                <div
                  class="item"
                  style="display: flex;flex-direction: column; align-items: flex-start;"
                >
                  <div class="value">{{ $t('pay_errorMsg') }}</div>
                  <div
                    class="key"
                    style="margin-top: 10px; padding-right: 20px;"
                  >
                    {{ payResult.failedReason }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 收据 -->
        <van-dialog v-model="isShowEmailDialog" :showConfirmButton="false">
          <el-form
            :model="ruleForm"
            :rules="emailRules"
            ref="eamilFormRef"
            label-position="top"
            class="el_form"
          >
            <div class="title">{{ $t('pay_emailReceiptText') }}</div>
            <el-form-item prop="receiptEmail">
              <el-input
                v-model="ruleForm.receiptEmail"
                type="email"
                :placeholder="$t('toast_requiredEmail')"
                clearable
              >
              </el-input>
            </el-form-item>
            <div class="btns">
              <div class="btn flex_center" @click="isShowEmailDialog = false">
                {{ $t('profile_cancel') }}
              </div>
              <div class="btn flex_center" @click="submitForm('eamilFormRef')">
                {{ $t('home_confirm') }}
              </div>
            </div>
          </el-form>
        </van-dialog>
        <bottom-button :custom="true" background="var(--card-bg)">
          <template v-slot:custom>
            <van-button
              v-if="
                payResult.success == 1 &&
                  payResult.paymentMethod != 8 &&
                  payResult.amount != 0
              "
              style=" margin-right:10px ; flex: 1;"
              round
              type="info"
              size="large"
              plain
              @click="showReceiptDialog"
              >{{ $t('order_receipt') }}</van-button
            >
            <template v-if="payResult.success == 1">
              <van-button
                v-if="payResult.type == 5 && actionType == 'rent'"
                style="flex: 1;"
                round
                type="info"
                size="large"
                @click="toScan"
                >{{ $t('home_scan2rent') }}</van-button
              >
              <van-button
                v-else
                style="flex: 1;"
                round
                type="info"
                size="large"
                @click="toHome"
                >{{ $t('order_homePage') }}</van-button
              >
            </template>
            <template v-else>
              <van-button
                style="flex: 1;"
                round
                type="info"
                size="large"
                @click="toPay"
                >{{ $t('home_gotoPay') }}</van-button
              >
            </template>
          </template>
        </bottom-button>
      </div>
    </div>
  </div>
</template>

<script>
import $api from '@/assets/js/api/index'
import share from '@/mixins/share'
export default {
  mixins: [share],
  data () {
    const validateEmail = (rule, value, callback) => {
      const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
      if (!value) {
        return callback(new Error(this.$t('toast_requiredEmail')))
      }
      setTimeout(() => {
        if (emailReg.test(value)) {
          callback()
        } else {
          callback(new Error(this.$t('toast_validEmail')))
        }
      }, 100)
    }
    return {
      actionType: 'back',
      payResult: null,
      orderInfo: null,

      payType: {
        1: 'pay_rental',
        5: 'wallet_deposit',
        7: 'pay_powerbank',
        13: 'pay_powerbank'
      },
      successTpye: {
        1: 'pay_paySucc',
        2: 'pay_payFail'
      },
      payMethodType: {
        1: 'pay_payByCard1',
        3: 'wallet_type_applepay',
        4: 'wallet_type_googlepay'
      },
      isShowEmailDialog: false,
      ruleForm: {
        receiptEmail: ''
      },
      emailRules: {
        receiptEmail: [{ validator: validateEmail, trigger: 'blur' }]
      },
      userInfo: null
    }
  },
  created () {
    this.getLang()
  },

  methods: {
    toPay () {
      this.$router.replace({
        path: '/pay/way',
        query: { type: this.payResult.type, orderNo: this.payResult.orderNo }
      })
      localStorage.setItem('pay_result', '')
    },
    showReceiptDialog () {
      this.isShowEmailDialog = true
      this.ruleForm.receiptEmail = this.userInfo.receiptEmail
    },
    getUserInfo () {
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      if (!userInfo) this.$router.replace('/login')
      this.userInfo = userInfo
    },
    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          const params = {
            id: '',
            orderNo: this.payResult.payOrderNo,
            receiptEmail: this.ruleForm.receiptEmail
          }
          $api.user.sentStripeEmail(params).then(res => {
            if (res.code != 0) {
              this.global.toast(res.message)
              return
            }
            this.userInfo.receiptEmail = this.ruleForm.receiptEmail
            localStorage.setItem('userInfo', JSON.stringify(this.userInfo));            
            this.global.toast(res.message)
            this.isShowEmailDialog = false
            this.toHome()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    toHome () {
      this.$router.replace('/home')
      localStorage.setItem('pay_result', '')
    },
    toScan () {
      this.$router.replace('/scan')
    },
    getOrderDetails () {
      return $api.order
        .getDetails({ orderNo: this.payResult.orderNo })
        .then(res => {
          if (res.code != '0') {
            this.global.toast(res.message)
            return
          }
          if (res.data) {
            this.orderInfo = res.data
          }
        })
    }
  },
  mounted () {
    this.actionType = localStorage.getItem('actionType') || 'back'
    this.getUserInfo()
    let params = JSON.parse(localStorage.getItem('pay_result'))
    if (params.isFree == 1) params.amount = 0
    this.payResult = params
    if ([1, 7, 13].includes(parseInt(params.type)) && params.orderNo) {
      this.$store.commit('startLoading')
      setTimeout(() => {
        this.$store.commit('endLoading')
        this.getOrderDetails()
      }, 1000)
    }
  },
  computed: {}
}
</script>
<style scoped lang="scss">
.container_page {
  margin: 0;
  background-color: var(--page-bg);
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
.result {
  .logo {
    width: 120px;
    height: 121.43px;
    margin: auto;
  }
  .tip {
    text-align: center;
    font-size: 20px;
    font-weight: Bold;
    color: var(--text-color);
  }
  .error {
    color: #889dbb;
  }
}

.box {
  padding-bottom: 150px;
}

.detail_card {
  padding: var(--gap);
  padding-bottom: 0px;
  .title {
    height: 20px;
    font-size: 17px;
    font-weight: 600;
    color: #39404d;
    margin-left: 10px;
    margin-bottom: 10px;
  }
  .list_box {
    background-color: var(--card-bg);
    padding-left: 20px;
    border-radius: 10px;
  }
  .row {
    .row-title {
      font-size: 15px;
      font-weight: 600;
      color: #39404d;
      padding-top: var(--gap);
    }
    &:first-child {
      border: none;
    }
    border-top: 1px #e4e4e6 solid;
  }
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 14px 0;

    .key {
      font-size: 13px;
      font-weight: 500;
      text-align: left;
      color: #66666b;
      display: flex;
      align-items: center;
      .label {
        transform: translateY(1px);
      }
      img {
        width: 14px;
        height: 14px;
        margin-right: 6px;
      }
    }
    .value {
      font-size: 15px;
      color: #39404d;
      font-weight: 600;
      padding-right: 20px;
      flex: 1;
      text-align: right;
    }
  }
}

.divider {
  height: 1px;
  background: #d2d8e2;
}
.fail {
  color: #889dbb;
}
</style>
